package com.example.taobaou.presenter.impl;

import android.util.Log;

import com.example.taobaou.model.Api;
import com.example.taobaou.model.domain.HomePagerContent;
import com.example.taobaou.presenter.ICategoryPagerPresenter;
import com.example.taobaou.utils.RetrofitManager;
import com.example.taobaou.utils.UrlUtils;
import com.example.taobaou.view.ICategoryPagerCallback;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class CategoryPagerPresenterImpl implements ICategoryPagerPresenter {

    private static final String TAG = "CPPresenterImpl.class";
    private Map<Integer, Integer> pagesInfo = new HashMap<>();
    private static final int DEFUALT_PAGE = 1;
    private Integer currentPage;



    @Override
    public void getCotentByCategoruId(int categoryId) {

        for (ICategoryPagerCallback callback : callbacks) {
            if (callback.getCategoryId() == categoryId) {
                callback.onLoading();
            }
        }

        //根据id加载内容
        Integer targetPage = pagesInfo.get(categoryId);
        if (targetPage == null) {
            targetPage = DEFUALT_PAGE;
            pagesInfo.put(categoryId, targetPage);
        }
        Call<HomePagerContent> task = createTask(categoryId, targetPage);
        task.enqueue(new Callback<HomePagerContent>() {
            @Override
            public void onResponse(Call<HomePagerContent> call, Response<HomePagerContent> response) {
                int code = response.code();
//                Log.d(TAG, "code---->" + code);
                if (code == HttpURLConnection.HTTP_OK) {
                    HomePagerContent pageContent = response.body();
//                    Log.d(TAG, "pageContent" + pageContent);
                    //把数据给到UI更新
                    handleHomePagerContentResult(pageContent, categoryId);
                } else {
                    handleNetWorkError(categoryId);
                }
            }

            @Override
            public void onFailure(Call<HomePagerContent> call, Throwable t) {
                Log.d(TAG, "t---->" + t.toString());
                handleNetWorkError(categoryId);
            }
        });
    }

    private Call<HomePagerContent> createTask(int categoryId, Integer targetPage) {
        String homePagerUrl = UrlUtils.createHomePagerUrl(categoryId, targetPage);
//        Log.d(TAG, "homePagerUrl----->" + homePagerUrl);
        Retrofit retrofit = RetrofitManager.getInstance().getRetrofit();
        Api api = retrofit.create(Api.class);
        return api.getHomePagerContent(homePagerUrl);
    }

    private void handleNetWorkError(int categoryId) {
        for (ICategoryPagerCallback callback : callbacks) {
            if (callback.getCategoryId() == categoryId) {
                callback.onNatworkError();
            }
        }
    }

    private void handleHomePagerContentResult(HomePagerContent pageContent, int categoryId) {
        //通知UI层更新界面
        List<HomePagerContent.DataBean> data = pageContent.getData();
        for (ICategoryPagerCallback callback : callbacks) {
            if (callback.getCategoryId() == categoryId) {
                if (pageContent == null || pageContent.getData().size() == 0) {
                    callback.onEmpty();
                } else {
                    callback.onContentLoaded(data);
                    List<HomePagerContent.DataBean> dataBeans = data.subList(data.size() - 5, data.size());
                    callback.onLooperListLoaded(dataBeans);


                }
            }
        }
    }

    @Override
    public void loaderMore(int categoryId) {
        //加载更多数据
        //1拿到当前页码

        currentPage = pagesInfo.get(pagesInfo);
        if (currentPage == null) {
            currentPage = 1;
        }
        //2页码++
        currentPage++;
        //3加载数据
        Call<HomePagerContent> task = createTask(categoryId, currentPage);
        //4处理数据结果
        task.enqueue(new Callback<HomePagerContent>() {
            @Override
            public void onResponse(Call<HomePagerContent> call, Response<HomePagerContent> response) {
                //成功的结果
                int code = response.code();
//                Log.d(TAG, "LoderMore.code------>" + code);
                if (code == HttpURLConnection.HTTP_OK) {
                    HomePagerContent result = response.body();
//                    Log.d(TAG, "result------>"+result.toString());
                    handleLoaderMoreResult(result, categoryId);
                } else {
                    //请求失败
                    handleLoaderMoreError(categoryId);
                }
            }

            @Override
            public void onFailure(Call<HomePagerContent> call, Throwable t) {
                //失败
                Log.d(TAG, t.toString());
                handleLoaderMoreError(categoryId);
            }
        });
    }

    private void handleLoaderMoreResult(HomePagerContent result, int categoryId) {
        for (ICategoryPagerCallback callback : callbacks) {
            if (callback.getCategoryId() == categoryId) {
                if (result == null || result.getData().size() == 0) {
                    callback.onLoadMoreEmptyt();
                } else {
                    callback.onLoadMoreLoaded(result.getData());
                }
            }
        }
    }

    private void handleLoaderMoreError(int categoryId) {
        currentPage--;
        pagesInfo.put(categoryId, currentPage);
        for (ICategoryPagerCallback callback : callbacks) {
            if (callback.getCategoryId() == categoryId) {
                callback.onLoadMoreErroor();
            }
        }
    }

    @Override
    public void reLoad(int categoryId) {

    }

    @Override
    public void onRefreshLoaderMore(int materialId) {

    }

    private List<ICategoryPagerCallback> callbacks = new ArrayList<>();

    @Override
    public void registerViewCallback(ICategoryPagerCallback callback) {
        if (!callbacks.contains(callback)) {
            callbacks.add(callback);
        }

    }

    @Override
    public void unregisiterViewCallback(ICategoryPagerCallback callback) {
        callbacks.remove(callback);
    }
}
